<template>
  <div class="students-page">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <span>学员管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增学员
          </el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form
        :model="searchForm"
        :inline="true"
        class="search-form"
      >
        <el-form-item label="学员姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入学员姓名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="潜在学员" value="potential" />
            <el-option label="已报名" value="enrolled" />
            <el-option label="已毕业" value="graduated" />
            <el-option label="已退学" value="dropped" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        class="table-container"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="province" label="省份" width="100" />
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160" />
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="info"
                size="small"
                @click="handleViewDetail(row)"
                title="查看详情"
              >
                详情
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
                title="编辑学员"
              >
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="handleFollowUp(row)"
                title="跟进记录"
              >
                跟进
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
                title="删除学员"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
        class="form-container"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="省份" prop="province">
          <el-input v-model="form.province" placeholder="请输入省份" />
        </el-form-item>
        
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入来源" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="潜在学员" value="potential" />
            <el-option label="已报名" value="enrolled" />
            <el-option label="已毕业" value="graduated" />
            <el-option label="已退学" value="dropped" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 学员详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="学员详细信息"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="studentDetail" class="student-detail">
        <!-- 学员基本信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="姓名">{{ studentDetail.student.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ studentDetail.student.gender }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ studentDetail.student.phone }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ studentDetail.student.email || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="省份">{{ studentDetail.student.province || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="来源">{{ studentDetail.student.source || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(studentDetail.student.status)">
                {{ getStatusText(studentDetail.student.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
        
        <!-- 统计信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>统计信息</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ studentDetail.statistics.total_orders }}</div>
                <div class="stat-label">总订单数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">¥{{ studentDetail.statistics.total_should_pay.toFixed(2) }}</div>
                <div class="stat-label">应缴总额</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">¥{{ studentDetail.statistics.total_paid.toFixed(2) }}</div>
                <div class="stat-label">已缴总额</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">¥{{ studentDetail.statistics.unpaid_amount.toFixed(2) }}</div>
                <div class="stat-label">未缴金额</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- 课程和订单信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>课程和订单信息</span>
            </div>
          </template>
          
          <div v-if="studentDetail.orders.length === 0" class="no-data">
            <el-empty description="暂无课程信息" />
          </div>
          
          <div v-else>
            <el-collapse v-model="activeCollapse">
              <el-collapse-item 
                v-for="order in studentDetail.orders" 
                :key="order.id"
                :title="`${order.course.name} - ${order.order_no}`"
                :name="order.id"
              >
                <template #title>
                  <div class="collapse-title">
                    <div class="title-main">
                      <span class="course-name">{{ order.course.name }}</span>
                      <span class="order-no">订单号: {{ order.order_no }}</span>
                    </div>
                    <el-tag :type="getOrderStatusType(order.status)" size="small">
                      {{ getOrderStatusText(order.status) }}
                    </el-tag>
                  </div>
                </template>
                
                <div class="order-detail">
                  <!-- 课程基本信息 -->
                  <el-descriptions :column="2" border size="small">
                    <el-descriptions-item label="课程名称">{{ order.course.name }}</el-descriptions-item>
                    <el-descriptions-item label="科目">{{ order.course.subject?.name || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="总阶段数">{{ order.course.total_stages }}</el-descriptions-item>
                    <el-descriptions-item label="课程总价">¥{{ order.course.total_price.toFixed(2) }}</el-descriptions-item>
                    <el-descriptions-item label="应缴金额">¥{{ order.should_pay_amount.toFixed(2) }}</el-descriptions-item>
                    <el-descriptions-item label="实缴金额">¥{{ order.actual_pay_amount.toFixed(2) }}</el-descriptions-item>
                    <el-descriptions-item label="支付方式">{{ order.payment_method || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="报名类型">{{ order.registration_type }}</el-descriptions-item>
                    <el-descriptions-item label="订单日期">{{ order.order_date }}</el-descriptions-item>
                    <el-descriptions-item label="报名时间">{{ order.enrollment_date || order.assignment?.enrollment_date || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="售前转化">{{ order.sales_employee?.name || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="售前团队负责人">{{ order.sales_team_leader?.name || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="运营人员">{{ order.reception_employee?.name || '未设置' }}</el-descriptions-item>
                    <el-descriptions-item label="业绩来源">{{ order.performance_source || '未设置' }}</el-descriptions-item>
                  </el-descriptions>
                  
                  <!-- 课程阶段信息 -->
                  <div class="stages-section">
                    <h4>课程阶段完成情况</h4>
                    <el-table :data="order.stages" size="small" border>
                      <el-table-column prop="stage_number" label="阶段" width="80" />
                      <el-table-column prop="stage_name" label="阶段名称" />
                      <el-table-column prop="stage_price" label="阶段价格" width="120">
                        <template #default="{ row }">
                          ¥{{ row.stage_price.toFixed(2) }}
                        </template>
                      </el-table-column>
                      <el-table-column label="完成状态" width="120">
                        <template #default="{ row }">
                          <el-tag :type="getProgressStatusType(row.progress.status)" size="small">
                            {{ getProgressStatusText(row.progress.status) }}
                          </el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column label="完成进度" width="120">
                        <template #default="{ row }">
                          <el-progress 
                            :percentage="row.progress.progress_percentage" 
                            :status="getProgressStatus(row.progress.status)"
                            :stroke-width="6"
                          />
                        </template>
                      </el-table-column>
                      <el-table-column label="开始时间" width="120">
                        <template #default="{ row }">
                          {{ row.progress.start_date ? formatDate(row.progress.start_date) : '-' }}
                        </template>
                      </el-table-column>
                      <el-table-column label="结束时间" width="120">
                        <template #default="{ row }">
                          {{ row.progress.end_date ? formatDate(row.progress.end_date) : '-' }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="description" label="描述" />
                    </el-table>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-card>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { safeAssign } from '@/utils/object'
import { getStudents, getStudentDetail, createStudent, updateStudent, deleteStudent, type Student } from '@/api/student'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()

// 详情对话框相关
const detailDialogVisible = ref(false)
const studentDetail = ref<any>(null)
const activeCollapse = ref<string[]>([])


// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref<Student[]>([])

// 表单数据
const form = reactive({
  id: null,
  name: '',
  gender: '',
  phone: '',
  email: '',
  province: '',
  source: '',
  status: 'potential'
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 方法
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    potential: 'info',
    enrolled: 'success',
    graduated: 'primary',
    dropped: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    potential: '潜在学员',
    enrolled: '已报名',
    graduated: '已毕业',
    dropped: '已退学'
  }
  return statusMap[status] || status
}

const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    refunded: '已退款',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getOrderStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    paid: 'success',
    refunded: 'info',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

const getProgressStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    not_started: 'info',
    in_progress: 'warning',
    completed: 'success',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

const getProgressStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    not_started: '未开始',
    in_progress: '进行中',
    completed: '已完成',
    failed: '未通过'
  }
  return textMap[status] || status
}

const getProgressStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    not_started: '',
    in_progress: '',
    completed: 'success',
    failed: 'exception'
  }
  return statusMap[status] || ''
}

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.status = ''
  handleSearch()
}

const handleAdd = () => {
  dialogTitle.value = '新增学员'
  form.id = null
  form.name = ''
  form.gender = ''
  form.phone = ''
  form.email = ''
  form.province = ''
  form.source = ''
  form.status = 'potential'
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogTitle.value = '编辑学员'
  // 使用安全的对象复制，避免数字键问题
  safeAssign(form, row, [
    'id', 'name', 'gender', 'phone', 'email', 'province', 'source', 'status'
  ])
  dialogVisible.value = true
}

const handleFollowUp = (row: any) => {
  ElMessage.info('跟进功能开发中')
}


const handleViewDetail = async (row: any) => {
  try {
    loading.value = true
    
    // 先尝试调用真实API
    try {
      const response = await getStudentDetail(row.id)
      studentDetail.value = response
    } catch (apiError) {
      
      // 如果API调用失败，使用模拟数据作为备选
      studentDetail.value = {
        student: {
          id: row.id,
          name: row.name,
          gender: row.gender,
          phone: row.phone,
          email: row.email || '未设置',
          province: row.province || '未设置',
          source: row.source || '未设置',
          status: row.status,
          created_at: row.created_at,
          updated_at: row.updated_at
        },
        orders: [
          {
            id: 1,
            order_no: 'ORD202401150001',
            course: {
              id: 1,
              name: 'Python基础课程',
              total_stages: 4,
              total_price: 2999.00,
              description: 'Python编程基础课程',
              status: 'active',
              subject: {
                id: 1,
                name: 'Python'
              }
            },
            stages: [
              { id: 1, stage_number: 1, stage_name: 'Python基础语法', stage_price: 799.00, description: '学习Python基本语法' },
              { id: 2, stage_number: 2, stage_name: '数据结构与算法', stage_price: 799.00, description: '学习基本数据结构' },
              { id: 3, stage_number: 3, stage_name: '面向对象编程', stage_price: 799.00, description: '学习OOP概念' },
              { id: 4, stage_number: 4, stage_name: '项目实战', stage_price: 602.00, description: '综合项目练习' }
            ],
            payment_method: '支付宝',
            registration_type: '新报名',
            should_pay_amount: 2999.00,
            actual_pay_amount: 2999.00,
            order_date: '2024-01-15T10:30:00',
            status: 'paid',
            sales_employee: { id: 1, name: '张三', employee_no: 'EMP001' },
            reception_employee: { id: 2, name: '李四', employee_no: 'EMP002' },
            performance_source: '线上推广'
          }
        ],
        statistics: {
          total_orders: 1,
          total_should_pay: 2999.00,
          total_paid: 2999.00,
          unpaid_amount: 0.00
        }
      }
    }
    
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取学员详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个学员吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteStudent(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (form.id) {
          // 更新学员
          await updateStudent(form.id, {
            name: form.name,
            gender: form.gender,
            phone: form.phone,
            email: form.email,
            province: form.province,
            source: form.source,
            status: form.status
          })
          ElMessage.success('更新成功')
        } else {
          // 创建学员
          await createStudent({
            name: form.name,
            gender: form.gender,
            phone: form.phone,
            email: form.email,
            province: form.province,
            source: form.source,
            status: form.status
          })
          ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  loadData()
}

const loadData = async () => {
  try {
    loading.value = true
    const response = await getStudents({
      page: pagination.currentPage,
      size: pagination.pageSize,
      name: searchForm.name,
      phone: searchForm.phone,
      status: searchForm.status
    })
    
    tableData.value = response.items
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('获取学员列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.students-page {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
  }
  
  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 4px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  
  /* 操作按钮布局优化 */
  .action-buttons {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    gap: 4px;
    width: 100%;
    
    .el-button {
      margin: 0;
      padding: 4px 6px;
      font-size: 11px;
      min-width: auto;
      height: 26px;
      line-height: 1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

/* 学员详情样式 */
.student-detail {
  .detail-card {
    margin-bottom: 20px;
    
    .card-header {
      font-weight: bold;
      font-size: 16px;
    }
  }
  
  .stat-item {
    text-align: center;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
    
    .stat-number {
      font-size: 24px;
      font-weight: bold;
      color: #409eff;
      margin-bottom: 8px;
    }
    
  .stat-label {
    font-size: 14px;
    color: #666;
  }
  
  .collapse-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    
    .title-main {
      display: flex;
      flex-direction: column;
      gap: 4px;
      
      .course-name {
        font-weight: bold;
        font-size: 16px;
        color: #303133;
      }
      
      .order-no {
        font-size: 12px;
        color: #909399;
        font-family: monospace;
      }
    }
  }
  
  .stages-section {
    margin-top: 20px;
    
    h4 {
      margin-bottom: 15px;
      color: #303133;
      font-size: 16px;
    }
  }
  
  .no-data {
    text-align: center;
    padding: 40px;
  }
}
  
  .order-detail {
    .stages-section {
      margin-top: 20px;
      
      h4 {
        margin-bottom: 15px;
        color: #333;
        font-size: 16px;
      }
    }
  }
  
  .no-data {
    text-align: center;
    padding: 40px;
  }
}
</style>
